package cz.af.portletExams.backend.rest.converter;

import cz.af.portletExams.backend.rest.dto.RegisteredExams;
import org.jdom.Element;
import org.jdom.Namespace;

import java.util.ArrayList;
import java.util.List;

public class RegistredExamsConverter extends GenericExamModelConverter<RegisteredExams> {

    @Override
    protected RegisteredExams convertToObject(Element rootElement) {
        final RegisteredExams registeredExams = new RegisteredExams();

        final Namespace atomNamespace = rootElement.getNamespace();
        final Namespace defaultNamespace = rootElement.getNamespace("");
        final Namespace xlinkNamespace = rootElement.getNamespace("xlink");

        final List<String> ids = new ArrayList<String>();
        registeredExams.setExamsIds(ids);

        final List<Element> entries = rootElement.getChildren("entry", atomNamespace);
        for (Element entry : entries) {
            final Element content = entry.getChild("content", atomNamespace);
            final Element exam = content.getChild("exam", defaultNamespace);
            if (exam != null) {
                final String href = exam.getAttribute("href", xlinkNamespace).getValue();
                final String[] strings = href.split("/");
                ids.add(strings[1]);
            }
        }
        return registeredExams;
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return RegisteredExams.class == clazz;
    }
}
